<template>
  <div id="login-card">
    <el-row>
      <el-col :span="8"><label for="email">邮箱:</label></el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-input
          id="email"
          v-model="email"
          placeholder="请输入电子邮箱"
        ></el-input>
      </el-col>
    </el-row>

    <el-row>
      <el-col :span="8"> <label for="code">验证码:</label></el-col>
    </el-row>
    <el-row>
      <el-col :span="24">
        <el-input
          id="code"
          placeholder="请输入邮箱验证码"
          v-model="code"
          show-password
        ></el-input>
      </el-col>
    </el-row>

    <!-- <el-row>
      <el-col :span="8"> <label>验证码:</label></el-col>
    </el-row> -->
    <el-row>
      <el-col :span="10">
        <el-link type="success" v-if="cdTime <= 0" @click="sendCode"
          >点击发送验证码</el-link
        >
        <div v-else>{{ cdTime }}秒可重发验证码</div>
      </el-col>
    </el-row>

    <el-row style="line-height: 15px"><hr /></el-row>

    <el-row>
      <el-col :span="24">
        <el-button @click="login" type="success" style="width: 100%"
          >登录</el-button
        >
      </el-col>
    </el-row>
  </div>
</template>

<script>
export default {
  name: "ByUserName",
  data() {
    return {
      cdTime: 0,
      email: "",
      code: "",
      checkCode: "",
      sendCodeUrl: "http://localhost:8081/sys-user/emailCodeSend",
      loginUrl: "http://localhost:8081/sys-user/emailLogin",
    };
  },
  methods: {
    login() {
      let that = this;
      $.ajax({
        url: that.loginUrl,
        contentType:"application/x-www-form-urlencoded",
        type: "post",
        xhrFields: {
          withCredentials: true,
        },
        data: {
          userEmail: that.email,
          emailCode: that.code,
        },
        success(data) {
          if(data==='success'){
          that.$router.replace("/");
          location.reload();
          }
        },
        error(){
          console.log("error");  
        }
      });
    },
    sendCode() {
      let that = this;
      $.ajax({
        url: that.sendCodeUrl,
        xhrFields: {
          withCredentials: true,
        },
        contentType: "application/json",
        data: {
          userEmail: that.email,
        },
        success(data) {
          if ((data = "ok")) {
            that.cdTime = 60;
            setInterval(function () {
              that.cdTime--;
            }, 1000);
          }
        },
        error() {
          console.log("error");
        },
      });
    },
  },
};
</script>

<style>
.el-row {
  margin: 5px;
}

label {
  font-size: 12px;
}

#login-card {
  height: inherit;
  width: inherit;
}
</style>